<template>
  <div class="arbitration-container">
    <n-card title="劳动仲裁代写服务" class="arbitration-card">
      <template #header-extra>
        <n-tag type="success" size="small">
          ¥4.9
        </n-tag>
      </template>

      <n-steps
        :current="currentStep"
        size="medium"
      >
        <n-step
          title="基本信息"
          description="填写申请人和被申请人信息"
          :status="currentStep === 1 ? 'process' : currentStep > 1 ? 'finish' : 'wait'"
        />
        <n-step
          title="仲裁请求"
          description="选择仲裁请求类型和具体内容"
          :status="currentStep === 2 ? 'process' : currentStep > 2 ? 'finish' : 'wait'"
        />
        <n-step
          title="事实和理由"
          description="描述劳动争议的具体情况"
          :status="currentStep === 3 ? 'process' : currentStep > 3 ? 'finish' : 'wait'"
        />
        <n-step
          title="生成仲裁书"
          description="确认信息并生成仲裁书"
          :status="currentStep === 4 ? 'process' : 'wait'"
        />
      </n-steps>

      <div class="step-content" style="margin-top: 20px; padding: 20px;">
        <!-- 步骤1：基本信息 -->
        <div v-show="currentStep === 1">
          <n-form
            ref="basicFormRef"
            :model="formData.basic"
            :rules="basicRules"
            label-placement="left"
            label-width="100"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="申请人姓名" path="applicantName">
              <n-input v-model:value="formData.basic.applicantName" placeholder="请输入申请人姓名" />
            </n-form-item>
            <n-form-item label="申请人电话" path="applicantPhone">
              <n-input v-model:value="formData.basic.applicantPhone" placeholder="请输入申请人电话" />
            </n-form-item>
            <n-form-item label="被申请人" path="respondentName">
              <n-input v-model:value="formData.basic.respondentName" placeholder="请输入被申请人（公司）名称" />
            </n-form-item>
            <n-form-item label="公司地址" path="respondentAddress">
              <n-input v-model:value="formData.basic.respondentAddress" placeholder="请输入被申请人地址" />
            </n-form-item>
          </n-form>
        </div>

        <!-- 步骤2：仲裁请求 -->
        <div v-show="currentStep === 2">
          <n-form
            ref="requestFormRef"
            :model="formData.request"
            :rules="requestRules"
          >
            <n-form-item label="仲裁请求类型" path="type">
              <n-select
                v-model:value="formData.request.type"
                :options="requestTypes"
                placeholder="请选择仲裁请求类型"
              />
            </n-form-item>
            <n-form-item label="具体请求内容" path="amount">
              <n-input-number
                v-model:value="formData.request.amount"
                prefix="¥"
                :min="0"
                :precision="2"
              />
            </n-form-item>
<!--            <n-form-item label="请求项目" path="items">-->
<!--              <draggable-->
<!--                v-model="formData.request.items"-->
<!--                item-key="id"-->
<!--                class="request-items-list"-->
<!--              >-->
<!--                <template #item="{ element }">-->
<!--                  <div class="request-item">-->
<!--                    <n-input-->
<!--                      v-model:value="element.name"-->
<!--                      placeholder="请输入请求项目名称"-->
<!--                    />-->
<!--                    <n-button-->
<!--                      circle-->
<!--                      type="error"-->
<!--                      size="small"-->
<!--                      @click="removeRequestItem(element.id)"-->
<!--                    >-->
<!--                      <template #icon>-->
<!--                        <n-icon><close /></n-icon>-->
<!--                      </template>-->
<!--                    </n-button>-->
<!--                  </div>-->
<!--                </template>-->
<!--              </draggable>-->
<!--              <div class="add-item-button">-->
<!--                <n-button-->
<!--                  dashed-->
<!--                  type="primary"-->
<!--                  @click="addRequestItem"-->
<!--                >-->
<!--                  添加请求项目-->
<!--                </n-button>-->
<!--              </div>-->
<!--            </n-form-item>-->
          </n-form>
        </div>

        <!-- 步骤3：事实和理由 -->
        <div v-show="currentStep === 3">
          <n-form
            ref="factFormRef"
            :model="formData.fact"
            :rules="factRules"
          >
            <n-form-item label="入职时间" path="startDate">
              <n-date-picker
                v-model:value="formData.fact.startDate"
                type="date"
                :format="dateFormat"
                placeholder="请选择入职时间"
                @update:value="handleDateChange($event, 'startDate')"
              />
            </n-form-item>
            <n-form-item label="离职时间" path="endDate">
              <n-date-picker
                v-model:value="formData.fact.endDate"
                type="date"
                :format="dateFormat"
                placeholder="请选择离职时间"
                @update:value="handleDateChange($event, 'endDate')"
              />
            </n-form-item>
            <n-form-item label="具体情况说明" path="description">
              <n-input
                v-model:value="formData.fact.description"
                type="textarea"
                placeholder="请详细描述劳动争议的具体情况"
                :rows="4"
              />
            </n-form-item>
          </n-form>
        </div>

        <!-- 步骤4：生成仲裁书 -->
        <div v-show="currentStep === 4">
          <n-alert
            v-if="!paymentStatus || paymentStatus === 'unpaid'"
            type="info"
            title="确认信息"
            style="margin-bottom: 20px"
          >
            请确认以下信息无误，确认后点击支付按钮生成仲裁书
          </n-alert>

          <n-descriptions bordered>
            <n-descriptions-item label="申请人">
              {{ formData.basic.applicantName }}
            </n-descriptions-item>
            <n-descriptions-item label="申请人电话">
              {{ formData.basic.applicantPhone }}
            </n-descriptions-item>
            <n-descriptions-item label="被申请人">
              {{ formData.basic.respondentName }}
            </n-descriptions-item>
            <n-descriptions-item label="被申请人地址">
              {{ formData.basic.respondentAddress }}
            </n-descriptions-item>
            <n-descriptions-item label="仲裁请求">
              {{ getRequestTypeLabel(formData.request.type) }}
            </n-descriptions-item>
            <n-descriptions-item label="请求金额">
              ¥{{ formData.request.amount }}
            </n-descriptions-item>
            <n-descriptions-item label="入职时间">
              {{formatTimestampOnlyDay(formData.fact.startDate) }}
            </n-descriptions-item>
            <n-descriptions-item label="离职时间">
              {{ formatTimestampOnlyDay(formData.fact.endDate) }}
            </n-descriptions-item>
            <n-descriptions-item label="具体情况">
              {{ formData.fact.description }}
            </n-descriptions-item>
          </n-descriptions>

          <div class="payment-section" style="margin-top: 20px">
            <template v-if="paymentStatus === 'unpaid'">
              <div class="price-box" style="text-align: center; margin: 20px 0;">
                <n-tag type="success" size="large">
                  服务费用：¥4.9
                </n-tag>
              </div>
            </template>

            <template v-if="paymentStatus === 'processing'">
              <div style="text-align: center; padding: 40px;">
                <n-spin size="large">
                  <template #description>
                    <n-text>正在生成仲裁书...</n-text>
                  </template>
                </n-spin>
              </div>
            </template>

            <template v-if="paymentStatus === 'completed'">
              <n-alert
                type="success"
                title="仲裁申请书已生成"
                style="margin-bottom: 20px"
              >
                您可以复制下方文本或下载文件
              </n-alert>
              <div class="arbitration-text">
                <n-input
                  type="textarea"
                  v-model:value="arbitrationText"
                  :rows="15"
                  readonly
                />
                <div class="text-actions" style="margin-top: 20px; text-align: center;">
                  <n-button
                    type="primary"
                    @click="() => {
                      navigator.clipboard.writeText(arbitrationText);
                      message.success('已复制到剪贴板');
                    }"
                  >
                    复制文本
                  </n-button>
                </div>
              </div>
            </template>
          </div>
        </div>

        <div class="step-actions">
          <n-space justify="end">
            <n-button
              v-if="currentStep > 1"
              @click="handlePrev"
            >
              上一步
            </n-button>
            <n-button
              v-if="currentStep < 4"
              type="primary"
              @click="handleNext"
            >
              下一步
            </n-button>
            <n-button
              v-if="currentStep === 4 && paymentStatus === 'unpaid'"
              type="primary"
              @click="handleSubmit"
              :loading="submitting"
            >
              立即支付
            </n-button>
          </n-space>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import request from '../utils/request'
import draggable from 'vuedraggable'
import { Close } from '@vicons/ionicons5'
import { nextTick } from 'vue';

const router = useRouter()
const userStore = useUserStore()
const message = useMessage()

// 步骤状态
const currentStep = ref(1)
const currentStatus = ref('process')

// 表单状态
const submitting = ref(false)
const paymentStatus = ref('unpaid')
const arbitrationText = ref('')

// 确保组件挂载时初始化状态
onMounted(() => {
  // 重置所有状态
  currentStep.value = 1
  currentStatus.value = 'process'
  submitting.value = false
  paymentStatus.value = 'unpaid'
  arbitrationText.value = ''

  // 重置表单数据
  formData.value = {
    basic: {
      applicantName: '',
      applicantPhone: '',
      respondentName: '',
      respondentAddress: ''
    },
    request: {
      type: '',
      amount: 0,
      items: []
    },
    fact: {
      startDate: null,
      endDate: null,
      description: ''
    }
  }
})

// 表单引用
const basicFormRef = ref(null)
const requestFormRef = ref(null)
const factFormRef = ref(null)

// 表单数据
const formData = ref({
  basic: {
    applicantName: '',
    applicantPhone: '',
    respondentName: '',
    respondentAddress: ''
  },
  request: {
    type: '',
    amount: 0,
    items: []
  },
  fact: {
    startDate: null,
    endDate: null,
    description: ''
  }
})

// 日期选择器格式化
const dateFormat = 'yyyy-MM-dd'

// 日期验证器
const validateDates = (rule, value) => {
  if (!value) {
    return new Error(rule.message)
  }
  if (rule.field === 'endDate' && formData.value.fact.startDate) {
    if (value < formData.value.fact.startDate) {
      return new Error('离职时间不能早于入职时间')
    }
  }
  return true
}

// 表单验证规则
const basicRules = {
  applicantName: {
    required: true,
    message: '请输入申请人姓名',
    trigger: ['blur', 'input']
  },
  applicantPhone: {
    required: true,
    message: '请输入申请人电话',
    trigger: ['blur', 'input']
  },
  respondentName: {
    required: true,
    message: '请输入被申请人名称',
    trigger: ['blur', 'input']
  },
  respondentAddress: {
    required: true,
    message: '请输入被申请人地址',
    trigger: ['blur', 'input']
  }
}

const requestRules = {
  type: {
    required: true,
    message: '请选择仲裁请求类型',
    trigger: ['blur', 'change']
  },
  amount: {
    required: true,
    validator: (rule, value) => {
      if (value === null || value === undefined || value === '') {
        return new Error('请输入具体请求金额')
      }
      if (value <= 0) {
        return new Error('请输入大于0的金额')
      }
      return true
    },
    trigger: ['blur', 'change']
  }
}

const factRules = {
  startDate: {
    required: true,
    message: '请选择入职时间',
    trigger: ['blur', 'change'],
    validator: validateDates
  },
  endDate: {
    required: true,
    message: '请选择离职时间',
    trigger: ['blur', 'change'],
    validator: validateDates,
    field: 'endDate'
  },
  description: {
    required: true,
    message: '请填写具体情况说明',
    trigger: ['blur', 'input']
  }
}

// 获取请求类型标签
const getRequestTypeLabel = (value) => {
  return requestTypes.value.find(item => item.value === value)?.label || ''
}

// function formatTimestamp(timestamp) {
//   const date = new Date(timestamp);
//   const year = date.getFullYear();
//   const month = (date.getMonth() + 1).toString().padStart(2, '0');
//   const day = date.getDate().toString().padStart(2, '0');
//   const hours = date.getHours().toString().padStart(2, '0');
//   const minutes = date.getMinutes().toString().padStart(2, '0');
//   const seconds = date.getSeconds().toString().padStart(2, '0');
//   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
// }

/**
 * 只格式化到日期
 * @param timestamp
 * @returns {string}
 */
function formatTimestampOnlyDay(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 处理下一步
// const handleNext = async () => {
//   try {
//     if (currentStep.value === 1) {
//       await basicFormRef.value?.validate()
//       currentStep.value++
//       console.log("currentStep.value--->"+currentStep.value++)
//       message.success('基本信息验证通过')
//     } else if (currentStep.value === 2) {
//       // 先验证金额
//       if (!formData.value.request.amount || formData.value.request.amount <= 0) {
//         message.error('请输入有效的请求金额')
//         return
//       }
//       await requestFormRef.value?.validate()
//       currentStep.value++
//       console.log("currentStep.value--->"+currentStep.value++)
//       message.success('仲裁请求验证通过')
//     } else if (currentStep.value === 3) {
//       await factFormRef.value?.validate()
//       currentStep.value++
//       console.log("currentStep.value--->"+currentStep.value++)
//       message.success('事实和理由验证通过')
//     }
//   } catch (error) {
//     console.error('表单验证失败:', error)
//     message.error('请检查表单填写是否正确')
//   }
// }

const handleNext = async () => {
  try {
    // 根据当前步骤验证表单
    let formRef;
    let formModel;
    let formRules;
    switch (currentStep.value) {
      case 1:
        formRef = basicFormRef;
        break;
      case 2:
        formRef = requestFormRef;

        break;
      case 3:
        formRef = factFormRef;

        break;
      default:
        return;
    }

    // 验证当前步骤的表单
    await formRef.value.validate();

    // 如果当前步骤验证通过，则进入下一个步骤
    // if (!formRef.value.valid) {
    //   message.error('请检查当前步骤的表单填写是否正确');
    //   return;
    // }
    if (currentStep.value < 4) {
      currentStep.value++;
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    message.error('请检查表单填写是否正确')
  }
}

// 处理上一步
const handlePrev = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!userStore.isLoggedIn) {
    message.warning('请先登录')
    // router.push('/login')
    return
  }

  /**
   * 翻译成正文
   */

  if(formData.value.fact && formData.value.fact.startDate ){
    formData.value.fact.startDate  = formatTimestampOnlyDay(formData.value.fact.startDate);
  }

  if(formData.value.fact && formData.value.fact.endDate ){
    formData.value.fact.endDate  = formatTimestampOnlyDay(formData.value.fact.endDate);
  }

  if(formData.value.request && formData.value.request.type ){
    formData.value.request.type  = getRequestTypeLabel(formData.value.request.type );
  }

  //提交创建订单
  const response  = await request.post('/api/order/new', {
    content: JSON.stringify(formData.value),
  })

  console.error(response.data)

  if (response.data.code !== 200){
    message.error(response.data.message)
    return
  }

  //跳转付款
  let resultUrl = response.data.data

  nextTick(() => {
    window.location.href = resultUrl;
  });

  // try {
  //   submitting.value = true
  //   paymentStatus.value = 'processing'
  //   await generateArbitrationText()
  //   message.success('支付成功，仲裁书已生成')
  // } catch (error) {
  //   console.error('提交失败:', error)
  //   message.error('提交失败，请重试')
  //   paymentStatus.value = 'unpaid'
  // } finally {
  //   submitting.value = false
  // }
}

// 处理日期变化
const handleDateChange = (date, type) => {
  console.log(`${type} changed to:`, date)
  formData.value.fact[type] = date
}

// 添加请求项目
const addRequestItem = () => {
  formData.value.request.items.push({
    id: Date.now(),
    name: ''
  })
}

// 删除请求项目
const removeRequestItem = (id) => {
  const index = formData.value.request.items.findIndex(item => item.id === id)
  if (index > -1) {
    formData.value.request.items.splice(index, 1)
  }
}

// 生成仲裁书文本
// const generateArbitrationText = async () => {
//   try {
//     // 这里应该调用后端API来生成仲裁书文本
//     // 临时模拟API调用
//     await new Promise(resolve => setTimeout(resolve, 2000))
//
//     // 根据表单数据生成仲裁书文本
//     arbitrationText.value = `
// 劳动仲裁申请书
//
// 申请人：${formData.value.basic.applicantName}
// 联系电话：${formData.value.basic.applicantPhone}
//
// 被申请人：${formData.value.basic.respondentName}
// 地址：${formData.value.basic.respondentAddress}
//
// 仲裁请求：
// 1. ${getRequestTypeLabel(formData.value.request.type)}
// 2. 要求支付金额：¥${formData.value.request.amount}
//
// 事实和理由：
// 本人于 ${formData.value.fact.startDate} 入职，于 ${formData.value.fact.endDate} 离职。
// ${formData.value.fact.description}
//
// 此致
// 劳动仲裁委员会
// `
//     paymentStatus.value = 'completed'
//     currentStatus.value = 'finish'
//   } catch (error) {
//     message.error('生成仲裁书失败，请重试')
//   }
// }

// 仲裁请求类型选项
const requestTypes = ref([
  {
    label: '未签订劳动合同二倍工资',
    value: 'double_salary'
  },
  {
    label: '违法解除劳动关系赔偿金',
    value: 'illegal_dismissal'
  },
  {
    label: '加班费',
    value: 'overtime_pay'
  },
  {
    label: '经济补偿金',
    value: 'severance_pay'
  }
])
</script>

<style scoped>
.arbitration-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.arbitration-card {
  margin-bottom: 20px;
}

.step-content {
  margin-top: 20px;
  padding: 20px;
}

.request-items-list {
  margin: 10px 0;
}

.request-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.text-actions {
  margin-top: 20px;
  text-align: center;
}

.price-box {
  text-align: center;
  margin: 20px 0;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .arbitration-container {
    padding: 10px;
  }

  .step-content {
    padding: 10px;
  }

  /* 调整表单布局 */
  :deep(.n-form) {
    width: 100%;
  }

  :deep(.n-form-item) {
    margin-bottom: 16px;
  }

  :deep(.n-form-item .n-form-item-label) {
    padding: 0 0 8px 0;
    margin-bottom: 4px;
    line-height: 1.5;
  }

  :deep(.n-form-item-label__text) {
    font-size: 14px;
  }

  /* 调整步骤条显示 */
  :deep(.n-steps) {
    padding: 0 10px;
  }

  :deep(.n-step-content__title) {
    font-size: 14px;
  }

  :deep(.n-step-content__description) {
    font-size: 12px;
  }

  /* 调整按钮组 */
  .step-actions {
    padding: 10px 0;
  }

  :deep(.n-space) {
    gap: 8px !important;
  }

  /* 调整描述列表 */
  :deep(.n-descriptions) {
    font-size: 14px;
  }

  :deep(.n-descriptions-table-header) {
    font-size: 12px;
  }

  /* 调整输入框和选择器 */
  :deep(.n-input),
  :deep(.n-select),
  :deep(.n-input-number) {
    width: 100%;
  }

  /* 调整请求项目列表 */
  .request-item {
    flex-wrap: wrap;
  }

  .request-item :deep(.n-input) {
    flex: 1;
    min-width: 0;
  }

  .request-item :deep(.n-button) {
    padding: 4px;
  }

  /* 调整文本区域 */
  :deep(.n-input__textarea) {
    min-height: 100px;
  }

  /* 调整日期选择器 */
  :deep(.n-date-picker) {
    width: 100%;
  }
}
</style>